package com.k2data.k2app.domain.serializer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.k2data.k2app.domain.DictDTO;
import com.k2data.k2app.utils.ObjectUtils;
import com.k2data.k2app.utils.StringUtils;

import java.io.IOException;
import java.util.Map;

/**
 * @author lidong9144@163.com 17-3-22.
 */
public class DictDTOSerializer extends JsonSerializer<DictDTO> {

    @Override
    public void serialize(DictDTO dictDTO, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        gen.writeStartObject();
        gen.writeNumberField("id", dictDTO.getId());
        gen.writeStringField("label", dictDTO.getLabel());
        gen.writeStringField("value", dictDTO.getValue());
        gen.writeStringField("sort", String.valueOf(dictDTO.getSort()));
        if (!StringUtils.isBlank(dictDTO.getType())) {
            gen.writeStringField("type", dictDTO.getType());
        }
        if (!StringUtils.isBlank(dictDTO.getTypeCn())) {
            gen.writeStringField("typeCn", dictDTO.getTypeCn());
        }

        if (!ObjectUtils.isEmpty(dictDTO.getExt())) {
            gen.writeStringField("ext", JSON.toJSONString(dictDTO.getExt(), SerializerFeature.DisableCircularReferenceDetect));
        }

        // 将 ext 里的键值对解析成和 label, value 同级的属性
        if (!ObjectUtils.isEmpty(dictDTO.getExtTrans())) {
            for (Map.Entry<String, String> entry : dictDTO.getExtTrans().entrySet()) {
                gen.writeObjectField(entry.getKey(), entry.getValue());
            }
        }

        gen.writeEndObject();
    }

}
